#include "PanoramicBondDealStruct.h"

BondDealInfo::BondDealInfo()
    : m_count(0), m_lastUpdate(0), m_cdcValue(-1e7), m_bytm(false) {
  memset(m_lastClose, 0, sizeof(m_lastClose));
}
BondDealInfo::BondDealInfo(const BondDealInfo& one) {
  m_count = one.m_count;
  m_lastUpdate = one.m_lastUpdate;
  m_cdcValue = one.m_cdcValue;
  memcpy(m_lastClose, one.m_lastClose, sizeof(m_lastClose));
  m_bytm = one.m_bytm;
}

void BondDealInfo::insert(sPanoramicBondDealUnit& unit) {
  auto it = std::find(m_tradeList.begin(), m_tradeList.end(), unit);
  if (it == m_tradeList.end()) {
    m_tradeList.push_back(unit);
  } else {
    *it = unit;
  }
  rebuildList();
}

void BondDealInfo::rebuildList() {
  m_count = 0;
  m_lastUpdate = 0;
  m_bytm = false;
  sort();
  auto it = m_tradeList.begin();
  if (it != m_tradeList.end()) {
    m_lastUpdate = it->m_updateTime;
  }
  for (auto it : m_tradeList) {
    if (atoi(it.m_dealStatus) < 4) m_count++;
    if (it.m_exercise[0] == '1') m_bytm = true;
  }
}

void BondDealInfo::sort() {
  class compare_deal_time {
   public:
    compare_deal_time() {}
    bool operator()(const sPanoramicBondDealUnit& unit1,
                    const sPanoramicBondDealUnit& unit2) {
      if (atoi(unit1.m_dealStatus) >= 4) {
        if (atoi(unit2.m_dealStatus) >= 4)
          return strcmp(unit1.m_id, unit2.m_id) > 0;
        return false;
      }
      if (atoi(unit2.m_dealStatus) >= 4) return true;
      return unit1.m_updateTime > unit2.m_updateTime;
    }
  };

  std::sort(m_tradeList.begin(), m_tradeList.end(), compare_deal_time());
}

CPanoramicBondDealMap::CPanoramicBondDealMap() {}

bool CPanoramicBondDealMap::isEmpty() {
  for (auto it : m_mapBondDeal) {
    if (!it.second.empty()) return false;
  }
  return true;
}

void CPanoramicBondDealMap::clear() { m_mapBondDeal.clear(); }

int CPanoramicBondDealMap::getDealCount(const int bondIndex) {
  for (auto& it : m_mapBondDeal) {
    const auto& itInfo = it.second.find(bondIndex);
    if (itInfo != it.second.end()) {
      return itInfo->second.m_count;
    }
  }
  return 0;
}

time_t CPanoramicBondDealMap::getLastUpdate(const int bondIndex) {
  for (auto& it : m_mapBondDeal) {
    const auto& itInfo = it.second.find(bondIndex);
    if (itInfo != it.second.end()) {
      return itInfo->second.m_lastUpdate;
    }
  }
  return 0;
}

const BondDealInfo& CPanoramicBondDealMap::getDealInfo(const int bondIndex) {
  static BondDealInfo dEmpty;
  for (auto& it : m_mapBondDeal) {
    const auto& itInfo = it.second.find(bondIndex);
    if (itInfo != it.second.end()) {
      return itInfo->second;
    }
  }
  return dEmpty;
}

MapDealInfo& CPanoramicBondDealMap::getBondDeal(int type) {
  if (m_mapBondDeal.find(type) == m_mapBondDeal.end()) {
    MapDealInfo mapInfo;
    m_mapBondDeal.insert(make_pair(type, mapInfo));
  }
  return m_mapBondDeal[type];
}